package com.example.xymarket.httpUtil;

import com.example.xymarket.common.HttpCon;
import com.example.xymarket.common.Info;
import com.example.xymarket.common.MyHandler;
import com.example.xymarket.common.MyJson;
import com.example.xymarket.common.MyUrl;
import com.example.xymarket.po.Order;
import com.example.xymarket.po.Result;
import com.example.xymarket.po.vo.OrderGoods;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderService {
    MyHandler myHandler;
    public OrderService(MyHandler myHandler1)
    {
        myHandler=myHandler1;
    }

    public void InsertOrder(List<OrderGoods> orderGoods)  {
        new Thread(new Runnable(){
            @Override
            public void run() {
                boolean co=true;
                for (OrderGoods orderGoods1 : orderGoods) {
                    Gson gson = new Gson();
                    String ordergoods = gson.toJson(orderGoods1);
                    Map<String, String> head = new HashMap<>();
                    head.put("Authorization", Info.getMyUserInfo().getToken());
                    try {
                        String Json = HttpCon.JsonPost(MyUrl.MarketUrl + "order/buy", ordergoods, head);
                        Type type = new TypeToken<Result<String>>() {
                        }.getType();
                        Result result = MyJson.getList(Json, type);
                        Integer code = result.getCode();
                        if (code != 0) {
                            co=false;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if(co)
                myHandler.getHandler().sendEmptyMessage(123);
                else myHandler.getHandler().sendEmptyMessage(-123);
            }
        }).start();
    }

    public void getOrder()  {
        new Thread(new Runnable(){
            @Override
            public void run() {
                Map<String ,String> head=new HashMap<>();
                head.put("Authorization", Info.getMyUserInfo().getToken());
                try {
                    String Json= HttpCon.OKPost(MyUrl.MarketUrl+"order/get_order",null,head,null);
                    Map<String,Object> result=MyJson.getOrder(Json);
                    if((Integer) result.get("code")==0)
                    {
                        List<Order> OrderList= (List<Order>) result.get("list");
                        android.os.Message message=new android.os.Message();
                        message.obj=OrderList;
                        message.what=132;
                        myHandler.getHandler().sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
